package org.example.mall.admin.configuration.auth.code;

import lombok.AllArgsConstructor;
import org.example.mall.admin.configuration.email.EmailEndpoint;
import org.example.mall.admin.constant.auth.AuthTypeConst;
import org.example.mall.admin.configuration.exception.BaseException;
import org.example.mall.admin.util.R;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author hzq
 * @date 2021/12/23 14:28
 */
@Component
@AllArgsConstructor
public class EmailSendCodeHandler extends AbstractSendCodeHandler {

    private static final List<String> SUPPORT_SCENES = new ArrayList<>(Arrays.asList(ScenesConst.LOGIN, ScenesConst.BIND));

    private final EmailEndpoint emailEndpoint;
    private final ThreadPoolTaskExecutor applicationTaskExecutor;

    @Override
    protected R<Object> handler(String scenes, String principal, String handlerType) {

        // 保存验证码到redis
        Code code = saveCodeToRedis(scenes, principal, handlerType);

        // 使用邮箱服务器发送验证码信息
        applicationTaskExecutor.submit(() -> emailEndpoint.sendEmailCode(principal, scenes, code.getCode()));

        return R.ofSuccessMessage("发送邮箱登录验证码成功");
    }

    @Override
    protected boolean supportType(String handlerType) {
        return AuthTypeConst.EMAIL.equals(handlerType);
    }

    @Override
    public Object checkScenes(String scenes, String principal, String handlerType) {

        // 用户使用邮箱登录时发送邮箱验证码 判断是否有该用户信息
        if (SUPPORT_SCENES.get(0).equals(scenes)) {
            if (getAuth(principal, handlerType) == null) {
                throw new BaseException("发送验证码失败、用户信息有误");
            }
        }

        // 用户修改绑定信息时
        if (SUPPORT_SCENES.get(1).equals(scenes)) {

        }

        return null;
    }

    @Override
    protected boolean supportScenes(String scenes) {
        return SUPPORT_SCENES.contains(scenes);
    }
}
